const logger = require('../../logger.js');
const { MessageBus } = require('../index.js');
const utility = require('../../utility.js');
class MessagePublisher extends MessageBus {
  constructor(exchangeName) {
    super();
    this.exchangeName = exchangeName;
    this.on('connection error', async () => {
      logger.debug('MessagePublisher will be tried again in 10 seconds...');
      await utility.takeRest(10000);
      try {
        await this.init();
        logger.debug('MessagePublisher reconnect success');
      } catch (err) {
        this.reset();
        logger.error('MessagePublisher reconnect failed', err);
        this.emit('connection error');
      }
    });
  }

  async initExchange() {
    await this.init();
    await this.channel.assertExchange(this.exchangeName, 'direct', {
      // durable: false,
    });
  }

  async publish(routingKey, data) {
    this.channel.publish(this.exchangeName, routingKey, Buffer.from(data, 'utf-8'));
  }

  static async createWebsocketMessageBus() {
    if (!MessagePublisher.websocketMessageBus) {
      MessagePublisher.websocketMessageBus = new MessagePublisher('ex_websocket');
      await MessagePublisher.websocketMessageBus.initExchange();
    }
    return MessagePublisher.websocketMessageBus;
  }
}

MessagePublisher.websocketMessageBus = null;

module.exports = {
  MessagePublisher,
};

exports = Object.assign(exports, module.exports);
